package com.usian.controller;

import com.usian.CartFeign;
import com.usian.config.RedisClient;
import com.usian.feign.ItemServiceFrign;
import com.usian.pojo.TbItem;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/frontend/cart")
public class CartController {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private ItemServiceFrign itemServiceFrign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_COOKIE_EXPIRE}")
    private Integer CART_COOKIE_EXPIRE;

    /**
     * 删除购物车的商品信息
     * @param userId
     * @param itemId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(@RequestParam String userId,@RequestParam String itemId,
                                     HttpServletRequest request,HttpServletResponse response){
        try {
            //判断用户是否登录
            if (StringUtils.isBlank(userId)){
                //未登录
                //获取购物车
                Map<String, TbItem> cart = getCartFromCookie(request);
                cart.remove(itemId);
                addClientCookie(request,response,cart);
            }else{
                //登录
                //获取购物车
                Map<String, TbItem> cart = getCartFromRedis(userId);
                cart.remove(itemId);
                addCartToRedis(cart,userId);
            }
            return Result.ok("删除成功");
        } catch (Exception e) {
            return Result.error("删除失败");
        }
    }

    /**
     * 购物车数量变化
     * @param userId
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("updateItemNum")
    public Result updateItemNum(@RequestParam String userId,@RequestParam String itemId,@RequestParam(defaultValue = "1") Integer num,
                                HttpServletRequest request,HttpServletResponse response){
        try {
            //判断用户有没有登录
            if (StringUtils.isBlank(userId)){
                //未登录
                //去查购物车
                Map<String, TbItem> cart = getCartFromCookie(request);
                //获取数据
                TbItem tbItem = cart.get(itemId);
                tbItem.setNum(num);
                //存回购物车
                cart.put(itemId,tbItem);
                //存回cookie
                addClientCookie(request,response,cart);
            }else{
                //登录
                //获取购物车
                Map<String, TbItem> cart = getCartFromRedis(userId);
                //获取数据
                TbItem tbItem = cart.get(itemId);
                tbItem.setNum(num);
                //存回购物车
                cart.put(itemId,tbItem);
                //存回redis
                addCartToRedis(cart,userId);
            }
            return Result.ok("修改成功");
        } catch (Exception e) {
            return Result.error("修改失败");
        }
    }

    /**
     * 查看购物车列表
     * @param userId
     * @return
     */
    @RequestMapping("showCart")
    public Result showCart(@RequestParam String userId,HttpServletRequest request){
        try {
            List<TbItem> list = new ArrayList<>();
            if (StringUtils.isBlank(userId)){
                //无登录
                Map<String, TbItem> cart = getCartFromCookie(request);
                for (TbItem tbItem : cart.values()) {
                    list.add(tbItem);
                }
            }else{
           /*     //获取cookie中有没有数据
                Map<String, TbItem> fromCookie = getCartFromCookie(request);
                if (fromCookie!=null && fromCookie.size()>0){
                    //如果有，添加到Redis中，
                    addCartCookieToRedis(fromCookie,userId);
                }
                // 判断redis中是否有同样的商品，如果有则修改商品数量，
                // 如果没有将商品信息查询出来，然后添加到redis中
*/
                //登录
                //获取购物车
                Map<String, TbItem> cart = getCartFromRedis(userId);
                for (TbItem tbItem : cart.values()) {
                    list.add(tbItem);
                }
            }
            return Result.ok(list);
        } catch (Exception e) {
            return Result.error("查看购物车失败");
        }
    }

/*    private void addCartCookieToRedis(Map<String, TbItem> fromCookie, String userId) {
        //先获取到redis中的数据
        Map<String, TbItem> fromRedis = getCartFromRedis(userId);
        for (String key : fromRedis.keySet()) {

        }
    }*/

    /**
     * 加入购物车
     * @param userId
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("addItem")
    public Result addItem( @RequestParam String userId, @RequestParam String itemId,
                         @RequestParam(defaultValue = "1")Integer num,HttpServletRequest request, HttpServletResponse response){
        try {
            //判断用户是否登录
            if (StringUtils.isBlank(userId)){
                //未登录
                //从cookie中查询商品列表
                Map<String, TbItem> cart = getCartFromCookie(request);
                //添加商品到购物车
                addItemToCart(cart,Long.valueOf(itemId),num);
                //写入cookie中
                addClientCookie(request,response,cart);
            }else{
                //登录
                //获取购物车
                Map<String,TbItem> cart = getCartFromRedis(userId);
                //添加商品到购物车
                addItemToCart(cart,Long.valueOf(itemId),num);
                //将购物车存放到redis中
                addCartToRedis(cart,userId);
            }
            return Result.ok("加入购物车成功");
        } catch (Exception e) {
            return Result.error("加入购物车失败");
        }
    }

    /**
     *  将购物车存放到redis中
     * @param userId
     */
    private void addCartToRedis(Map<String,TbItem> cart,String userId){
        cartFeign.addCartToRedis(cart,userId);
    }

    /**
     * 从reids中获取购物车
     * @param userId
     * @return
     */
    private Map<String,TbItem> getCartFromRedis(String userId){
        Map<String, TbItem> cart = cartFeign.getCartFromRedis(userId);
        if (cart!=null && cart.size()>0){
            //有购物车直接返回
            return cart;
        }
        //没有购物车，创建一个
        return new HashMap<String,TbItem>();
    }

    /**
     * 把购物车存到cookie中
     * @param request
     * @param response
     * @param cart
     */
    private void addClientCookie(HttpServletRequest request, HttpServletResponse response, Map<String, TbItem> cart) {
        String objectToJson = JsonUtils.objectToJson(cart);
        CookieUtils.setCookie(request,response,CART_COOKIE_KEY,objectToJson,CART_COOKIE_EXPIRE,true);
    }

    /**
     * 将商品添加到购物车
     * @param cart
     * @param itemId
     * @param num
     */
    private void addItemToCart(Map<String, TbItem> cart,Long itemId,Integer num){
        //从购物车中取商品
        TbItem tbItem = cart.get(itemId.toString());
        if(tbItem != null){
            //购物车中已经有该商品，商品数量相加
            tbItem.setNum(tbItem.getNum()+num);
        }else{
            //购物车中没有该商品。查询商品信息并添加该产品信息到购物车
            tbItem = itemServiceFrign.selectItemInfo(itemId);
            tbItem.setNum(num);
        }
        cart.put(itemId.toString(),tbItem);
    }

    /**
     * 获取购物车
     * @param request
     * @return
     */
    private Map<String, TbItem> getCartFromCookie(HttpServletRequest request){
        String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY,true);
        if (StringUtils.isNotBlank(cookieValue)){
            //购物车存在
            Map<String,TbItem> map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return map;
        }
        //不存在，创建一个
        return new HashMap<String,TbItem>();
    }
}
